package com.jse.ee;
import java.io.IOException;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.PushBuilder;

@WebFilter("/*")
public class PushFilter implements Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String uri = httpRequest.getRequestURI();
    System.out.println("Filtre pour uri " + uri + " : " + request.getProtocol());

    switch (uri) {
      case "/serverpush/maservlet":
        PushBuilder pushBuilder = httpRequest.newPushBuilder();
        if (pushBuilder != null) {
          System.out.println("Utilisation du push server pour uri " + uri + " : " + request.getProtocol());
          pushBuilder.path("main.css").push();
          pushBuilder.addHeader("content-type", "image/jpeg").path("images/logo.jpg").push();
        }
        break;
      default:
        break;
    }
    chain.doFilter(request, response);
  }
}